<template>
	<div class="speaker_detail" :style="`background-image:url(${$store.state.tenant.config.addSpeakerImage});`">
		<van-form input-align="right" ref="regForm" id="regContainer">
			<van-cell-group inset v-if="hasFieldGroup('base')">
				<van-sticky>
					<div class="progress">
						<van-progress :pivot-text="`表单完成度${fromProgress}%`" :percentage="fromProgress" stroke-width="8" />
					</div>
				</van-sticky>

				<van-field
          v-if="hasRegisterField('phone')"
					v-model="params.phone"
					:label="getRegisterField('phone').label"
					:placeholder="`请输入${getRegisterField('phone').label}`"
					type="tel"
					maxlength="11"
					:required="getRegisterField('phone').required"
					:readonly="!allowHandle"
					:rules="[{
            required: getRegisterField('phone').required,
            message: `请输入${getRegisterField('phone').label}`
          }]"
				/>

				<van-field
          v-if="hasRegisterField('title')"
					v-model="params.title"
          :label="getRegisterField('title').label"
					:placeholder="`请选择${getRegisterField('title').label}`"
					:required="getRegisterField('title').required"
					readonly
					@click="show.selectTitle = allowHandle ? true : false"
					:rules="[{
            required: getRegisterField('title').required,
            message: `请选择${getRegisterField('title').label}`
          }]"
				/>
				<!-- <van-field name="switch" label="手动输入科室">
					<template #input>
						<van-switch size="small" v-model="isDeptInput" />
					</template>
				</van-field> -->
				<van-field
          v-if="hasRegisterField('department')"
					v-model="params.department"
          :label="getRegisterField('department').label"
          :placeholder="`请输入${getRegisterField('department').label}`"
					:required="getRegisterField('department').required"
					:readonly="!allowHandle || !isDeptInput"
					:rules="[{
            required: getRegisterField('department').required,
            message: `请输入${getRegisterField('department').label}`
          }]"
				/>
				<!-- @click="show.selectDept = isDeptInput ? false : true" -->

				<van-field
          v-if="hasRegisterField('hospital')"
					ref="hospitalInput"
					v-model="params.hospital"
					:label="getRegisterField('hospital').label"
          :placeholder="`请输入${getRegisterField('hospital').label}`"
					:readonly="!allowHandle || hospitalReadonly"
          :required="getRegisterField('hospital').required"
					@click="hospitalReadonly ? show.hospitalPicker = true : show.hospitalPicker = false"
          :rules="[{
            required: getRegisterField('hospital').required,
            message: `请输入${getRegisterField('hospital').label}`
          }]"
				/>
				<!-- :readonly="hospitalReadonly" -->
			</van-cell-group>

			<!-- <van-field
				v-model="params.email"
				label="邮箱"
				placeholder="请输入邮箱"
				:required="isRequired"
				:rules="[
					{ required: true, message: '请填写邮箱' },
					{ pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '邮箱格式错误！'}
				]"
			/> -->

			<van-cell-group inset title="证件信息" v-if="hasFieldGroup('document')">
				<van-field
          v-if="hasRegisterField('idCardFront')"
          :label="getRegisterField('idCardFront').label"
          :required="getRegisterField('idCardFront').required"
          :rules="[{
            required: getRegisterField('idCardFront').required,
            message: `请上传${getRegisterField('idCardFront').label}`
          }]"
				>
					<template #input>
						<uploadMutipart
							@deleteFile="deleteFile"
							@uploadSucc="uploadSucc"
							:maxFileCount="1"
							:readonly="!allowHandle"
							type="idCardFront"
							:deletable="type === 'detail' ? false : true"
							:files="processImgArr(params.idCardFront)"
						></uploadMutipart>
					</template>
				</van-field>
				<van-field
          v-if="hasRegisterField('name')"
					v-model="params.name"
          :label="getRegisterField('name').label"
          :placeholder="`请输入${getRegisterField('name').label}`"
          :required="getRegisterField('name').required"
					:readonly="!allowHandle"
          :rules="[{
            required: getRegisterField('name').required,
            message: `请输入${getRegisterField('name').label}`
          }]"
				/>
				<van-field
          v-if="hasRegisterField('cardNumber')"
					v-model="params.cardNumber"
          :label="getRegisterField('cardNumber').label"
          :placeholder="`请输入${getRegisterField('cardNumber').label}`"
          :required="getRegisterField('cardNumber').required"
					:readonly="!allowHandle"
          :rules="[{
            required: getRegisterField('cardNumber').required,
            message: `请输入${getRegisterField('cardNumber').label}`
          }]"
				/>
				<van-field
          v-if="hasRegisterField('idCardRevers')"
          :label="getRegisterField('idCardRevers').label"
          :required="getRegisterField('idCardRevers').required"
          :rules="[{
            required: getRegisterField('idCardRevers').required,
            message: `请上传${getRegisterField('idCardRevers').label}`
          }]"
				>
					<template #input>
						<uploadMutipart
							@deleteFile="deleteFile"
							@uploadSucc="uploadSucc"
							:readonly="!allowHandle"
							:maxFileCount="1"
							type="idCardRevers"
							:deletable="type === 'detail' ? false : true"
							:files="processImgArr(params.idCardRevers)"
						></uploadMutipart>
					</template>
				</van-field>

				<van-field
          v-if="hasRegisterField('licensedPhysician')"
          :label="getRegisterField('licensedPhysician').label"
          :required="getRegisterField('licensedPhysician').required"
          :rules="[{
            required: getRegisterField('licensedPhysician').required,
            message: `请上传${getRegisterField('licensedPhysician').label}`
          }]"
				>
					<template #input>
						<uploadMutipart
							@deleteFile="deleteFile"
							@uploadSucc="uploadSucc"
							:maxFileCount="allowHandle ? 4 : processImgArr(params.licensedPhysician).length"
							:readonly="!allowHandle"
							type="licensedPhysician"
							:deletable="type === 'detail' ? false : true"
							:files="processImgArr(params.licensedPhysician)"
						></uploadMutipart>
					</template>
				</van-field>

        <van-field
          v-if="hasRegisterField('certificate')"
					v-model="params.certificate"
          :label="getRegisterField('certificate').label"
					:placeholder="`请输入${getRegisterField('certificate').label}`"
          :required="getRegisterField('certificate').required"
					:readonly="!allowHandle"
					:rules="[{
            required: getRegisterField('certificate').required,
            message: `请输入${getRegisterField('certificate').label}`
          }]"
				/>

				<van-field
          v-if="hasRegisterField('nameBadge')"
          :label="getRegisterField('nameBadge').label"
          :required="getRegisterField('nameBadge').required"
          :rules="[{
            required: getRegisterField('nameBadge').required,
            message: `请上传${getRegisterField('nameBadge').label}`
          }]"
				>
					<template #input>
						<uploadMutipart
							@deleteFile="deleteFile"
							@uploadSucc="uploadSucc"
							:maxFileCount="allowHandle ? 2 : processImgArr(params.nameBadge).length"
							:readonly="!allowHandle"
							type="nameBadge"
							:deletable="type === 'detail' ? false : true"
							:files="processImgArr(params.nameBadge)"
						></uploadMutipart>
					</template>
				</van-field>
			</van-cell-group>

			<van-cell-group inset title="银行卡账户信息" v-if="hasFieldGroup('account')">
				<van-field
          v-if="hasRegisterField('bankCard')"
          :label="getRegisterField('bankCard').label"
          :required="getRegisterField('bankCard').required"
          :rules="[{
            required: getRegisterField('bankCard').required,
            message: `请上传${getRegisterField('bankCard').label}`
          }]"
				>
					<template #input>
						<uploadMutipart
							@deleteFile="deleteFile"
							@uploadSucc="uploadSucc"
							:maxFileCount="allowHandle ? 4 : processImgArr(params.bankCard).length"
							:readonly="!allowHandle"
							type="bankCard"
							:deletable="type === 'detail' ? false : true"
							:files="processImgArr(params.bankCard)"
						></uploadMutipart>
					</template>
				</van-field>
				<van-field
          v-if="hasRegisterField('bankNumber')"
					v-model="params.bankNumber"
          :label="getRegisterField('bankNumber').label"
					:placeholder="`请输入${getRegisterField('bankNumber').label}`"
          :required="getRegisterField('bankNumber').required"
					:readonly="!allowHandle"
          :rules="[{
            required: getRegisterField('bankNumber').required,
            message: `请输入${getRegisterField('bankNumber').label}`
          }]"
				/>
				<van-field
          v-if="hasRegisterField('bankName')"
					v-model="params.bankName"
          :label="getRegisterField('bankName').label"
					:placeholder="`请选择${getRegisterField('bankName').label}`"
          :required="getRegisterField('bankName').required"
					readonly
					@click-input="clickSelectBankName"
				  :rules="[{
            required: getRegisterField('bankName').required,
            message: `请选择${getRegisterField('bankName').label}`
          }]"
				/>
				<van-field
          v-if="hasRegisterField('bankBranch')"
					v-model="params.bankBranch"
          :label="getRegisterField('bankBranch').label"
					:placeholder="`请输入${getRegisterField('bankBranch').label}`"
          :required="getRegisterField('bankBranch').required"
					:readonly="!allowHandle"
          :rules="[{
            required: getRegisterField('bankBranch').required,
            message: `请输入${getRegisterField('bankBranch').label}`
          }]"
				/>
			</van-cell-group>

			<van-cell-group inset title="邀请函照片，用于生成会议邀请函的讲者正面照片" v-if="hasFieldGroup('other')">
				<van-field
          v-if="hasRegisterField('avatar')"
          :label="getRegisterField('avatar').label"
          :required="getRegisterField('avatar').required"
					:rules="[{ validator: validateAvatar }]"
				>
					<template #input>
						<!-- <Cropper @cropSucc="cropSucc" :cropImg="cropImg"></Cropper> -->
            <div class="avatar-preview" v-if="params.avatar">
              <div class="avatar-preview_close" @click="clickDeleteAvatar">
                <van-icon name="cross" />
              </div>
              <img class="avatar-preview__inner" :src="`//${params.avatar}`" alt="">
            </div>
            <van-uploader v-else :after-read="uploadAvatar" />
					</template>
				</van-field>
			</van-cell-group>

			<!-- <van-cell-group inset title="参会信息" v-if="type === 'detail'">
				<van-field
					v-model="params.meetingNum"
					label="参会次数"
					readonly
				>
					<template #extra>
						<div class="pl-2">
							<van-icon @click="clickShowMeetingRecord" size="26" name="info" style="vertical-align: middle;" />
						</div>
					</template>
				</van-field>
			</van-cell-group> -->
		</van-form>


		<van-row
			v-if="allowHandle"
			class="mt-4 mb-8"
			:gutter="20"
			justify="center"
		>
			<van-col :span="20" style="visibility: hidden">
				<van-button block type="primary" style @click="onSubmitHandler">提交</van-button>
			</van-col>
			<van-col :span="20" class="handle_fixed">
				<van-row :gutter="20">
					<van-col :span="12">
						<van-button block type="default" style @click="saveStorageHandler">暂存</van-button>
					</van-col>
					<van-col :span="12">
						<van-button block type="primary" style @click="onSubmitHandler">提交</van-button>
					</van-col>
				</van-row>
			</van-col>
		</van-row>
	</div>

	<van-popup
		style="max-height:70%; min-height:70%"
		v-model:show="show.hospitalPicker"
		:close-on-click-overlay="false"
		:closeable="false"
		position="bottom">
		<hospital-select
			@inputHospital="inputHospital"
			@hospitalItemClick="hospitalItemClick($event)"
		></hospital-select>
	</van-popup>

	<van-action-sheet
		:closeable="false"
		:round="false"
		:close-on-click-overlay="false"
		v-model:show="show.selectDept"
	>
		<van-picker
			title="选择科室"
			:columns="constant.deptList"
			@confirm="confirmDept"
			@cancel="show.selectDept = false"
			@change="changeDept"
		/>
	</van-action-sheet>

	<van-action-sheet
		:closeable="false"
		:round="false"
		:close-on-click-overlay="false"
		v-model:show="show.selectTitle">
		<van-picker
			title="选择职称"
			:columns="constant.titleList"
			@confirm="confirmTitle"
			@cancel="show.selectTitle = false"
			@change="changeTitle"
		/>
	</van-action-sheet>

	<van-action-sheet
		class="m-vh"
		:closeable="false"
		:round="false"
		:close-on-click-overlay="false"
		v-model:show="show.doctorYhxy">
		<base-agree-doctor-yhxy @confirm="clickConfirmDoctorYhxy"></base-agree-doctor-yhxy>
	</van-action-sheet>

	<van-action-sheet
		class="m-vh"
		:closeable="false"
		:round="false"
		:close-on-click-overlay="false"
		v-model:show="show.doctorYszc">
		<base-agree-doctor-yszc
            @confirm="clickConfirmDoctorYszc"
            @cancel="clickConfirmDoctorYhxy(false)"
            ></base-agree-doctor-yszc>
	</van-action-sheet>

	<van-action-sheet
		class="m-vh"
		title="请在空白处签名"
		:closeable="false"
		:round="false"
		:close-on-click-overlay="false"
		v-model:show="show.sign">
		<base-sign @previous="clickConfirmDoctorYszc(false)" @uploadSucc="signUploadSuccess"></base-sign>
	</van-action-sheet>
	
	<!--预览裁剪及去除背景后的头像-->
	<van-dialog v-model:show="show.avatarPreview" title="照片预览" show-cancel-button @confirm="confirmPortrait">
		<van-notice-bar color="#1989fa" background="#ecf9ff" wrapable :scrollable="false" text="以下是裁剪后的照片，为了确保在邀请函中的最佳展示效果，在您点击确认按钮后，系统将使用AI智能去除照片背景，您也可以点击取消使用其他照片。"/>
		<van-image :src="params.avatar.indexOf('http') >= 0 ? params.avatar : '//' + params.avatar">
			<template v-slot:loading>
				<van-loading type="spinner" size="20" />
			</template>
		</van-image>
	</van-dialog>
	<van-dialog v-model:show="show.avatarPreviewCut" title="照片预览" @confirm="confirmCrop">
		<van-image :src="params.avatar.indexOf('http') >= 0 ? params.avatar : '//' + params.avatar">
			<template v-slot:loading>
				<van-loading type="spinner" size="20" />
			</template>
		</van-image>
	</van-dialog>

	<!-- 参会记录 -->
	<meeting-record ref="refMeetingRecord" />
	<!-- 选择开户行 -->
	<select-bank-name ref="selectBankName" @confirm="confirmSelectBankName"></select-bank-name>
	<!-- 选择省市区 -->
	<select-area ref="selectArea" @confirm="confirmSelectArea"></select-area>
	<div class="van-safe-area-bottom"></div>
</template>

<script>
import { defineComponent } from "vue"
import uploadMutipart from "@/components/uploadMutipart/index.vue"
import MeetingRecord from './components/meeting-record.vue'
import {showToast ,showNotify, showDialog, showConfirmDialog, showLoadingToast, showSuccessToast} from 'vant'
import SpeakerRegisterBg from '@/img/speaker_register_bg.jpg'
import Cropper from "@/components/cropper/index.vue"

export default defineComponent({
	components: { uploadMutipart, MeetingRecord, Cropper },
	inject: ['constant', 'api'],
	data() {
		return {
			show: {
				selectDept: false,
				doctorYhxy: false,
				doctorYszc: false,
				sign: false,
				hospitalPicker: false,
				avatarPreview: false,
				avatarPreviewCut: false
			},
			SpeakerRegisterBg,
			phone: '',
			isDeptInput: true,
			hospitalReadonly: false,
			curDept: null,
			curTitle: null,
			detail: null,
			params: {
				id: '',
				name: '',
				phone: '',
				hospital: '',
				cardNumber: '',
				department: '',
				title: '',
				bankName: '',
				bankBranch: '',
				bankNumber: '',
				idCardFront: [],
				idCardRevers: [],
				licensedPhysician: [], // 执业证书
        certificate: '',
				nameBadge: [], // 胸牌
				bankCard: [],
				avatar: '',
				photoJson: '',
				meetingNum: '',
				createUserId:'',
				openid:''
			},
			cropImg: '',
			loadingToast: {},
			fromProgress: 0
		}
	},
	computed: {
		type () {
			return this.$route.query.type
		},
		isRequired () {
			if (this.type == 'add') {
				document.title = '添加讲者'
				return true
			}
			if (this.type == 'update') {
				document.title = '修改讲者'
				return true
			}
			if (sessionStorage.getItem('isScan') == 'true') {
				document.title = '注册'
				return true
			}
			
			return false
		},
    //获取讲者字段配置
    getSpeakerRegConfig () {
      return JSON.parse(this.$store.state.tenant.config.speakerRegConfig)
    },
		// 是否允许操作
		allowHandle () {
			if ([3, 4].includes(this.params.status)){
				return true
			} else if(sessionStorage.getItem('isScan') === 'true'){
				return true
			}
			return ['add', 'update'].includes(this.type)
		}
	},
  created () {
    console.log(this.getSpeakerRegConfig)
  },
	mounted () {
		if(sessionStorage.getItem('isScan') === 'true' || this.$route.query.isScan) {
			const speakerId = localStorage.getItem('speakerId')
			speakerId && this.getSpeakerDetail(speakerId)
		}else {
			const speakerId = this.$route.params.id
			speakerId && this.getSpeakerDetail(speakerId)
		}
	},
	watch: {
        'params': {
            deep: true, //深度监听设置为 true
            handler: function(newV,oldV){
				      this.computeRegStep(newV)
            }
        }
    },
	methods: {
    getRegisterField(val) {
      return this.getSpeakerRegConfig.find(item => item.columnName == val);
    },
    // 是否存在指定注册字段
    hasRegisterField (val) {
      return !!this.getRegisterField(val);
    },
    // 是否显示组件组
    hasFieldGroup (val) {
      const fieldGroup = {
        base: ['phone', 'title', 'department', 'hospital'],
        document: ['idCardFront', 'name', 'cardNumber', 'idCardRevers', 'licensedPhysician', 'nameBadge'],
        account: ['bankCard', 'bankNumber', 'bankName', 'bankBranch'],
        other: ['avatar']
      }

      const list = fieldGroup[val] || [];

      return list.some(item => this.hasRegisterField(item))
    },
		validateAvatar() {
      const avatar = this.getRegisterField('avatar')
      if (avatar?.required) {
        if(!this.params.avatar){
          return '请上传照片'
        }
      } 
      return true
		},
		cropSucc(url) {
			if(url) {
				this.params.avatar = ''
				this.show.avatarPreview = true
        console.log('uri =-====>', url)
				this.params.avatar = url
			}
		},
    clickDeleteAvatar () {
      this.params.avatar = ''
    },
    uploadAvatar (file) {
      const formData = new FormData();
      formData.append("file", file.file);
      this.api.portraitV2Avatar(formData).then(res => {
        if (!res.code) {
          this.params.avatar = res.data
        }
      })
    },
		confirmPortrait() {
			this.loadingToast = showLoadingToast({
				message: 'AI智能处理中...',
				forbidClick: true,
				duration: 0
			})
			this.api.portrait({
				fileUrl: this.params.avatar.indexOf('http') >=0 ? this.params.avatar : 'http://' + this.params.avatar
			}).then(res => {
				this.loadingToast.close()
				if(res.code === 0) {
					this.show.avatarPreviewCut = true
					this.params.avatar = ''
					this.params.avatar = res.data
				}
			}).catch(() => {
				this.loadingToast.close()
			})
		},
		confirmCrop() {
			this.cropImg = this.params.avatar.indexOf('http') >=0 ? this.params.avatar : 'http://' + this.params.avatar
		},
		// 获取讲者详情
		async getSpeakerDetail (speakerId) {
			const res = await this.api.speakerDetail(speakerId)
			if (!res.code) {
        if (!res.data) {
          localStorage.removeItem('speakerId')
          return
        }
				this.detail = res.data
        if (sessionStorage.getItem('isScan') === 'true'){
          if (res.data.status == 1) {
            this.$router.replace('/vol/register-result')
            return
          }
        }
				Object.keys(this.params).forEach(key => {
					if (res.data[key]) this.params[key] = res.data[key]
				})
				this.params.meetingNum = this.params.meetingNum || 0

				if (res.data.photoJson) {
					const photoJsonArray = JSON.parse(res.data.photoJson)
					photoJsonArray.forEach(item => {
						switch (item.photoType + '') {
							case '1':
								this.params.idCardFront = item.url || []
								break
							case '2':
								this.params.idCardRevers = item.url || []
								break
							case '3':
								this.params.licensedPhysician = item.url || []
								break
							case '4':
								this.params.nameBadge = item.url || []
								break
							case '5':
								this.params.bankCard = item.url || []
								break
							case '6':
								// this.params.avatar = item.url || ''
								this.cropImg = item.url ? (item.url.indexOf('http') >=0 ? item.url : 'http://' + item.url || '') : ''
								break
						}
					})
				}
			}
		},
		// 点击选择开户行
		clickSelectBankName () {
			if (this.allowHandle) {
				this.$refs.selectBankName.init()
			}
		},
		// 确认选择开户行
		confirmSelectBankName (value) {
			this.params.bankName = value
		},
		// 点击选择省市区
		clickSelectArea () {
			this.$refs.selectArea.init()
		},
		// 确认选择省市区
		confirmSelectArea (value) {
			this.params.province = value[0].text
			this.params.provinceId = value[0].value

			this.params.city = value[1].text
			this.params.cityId = value[1].value

			this.params.area = value[2].text
			this.params.areaId = value[2].value
		},
		processImgArr(imgArr) {
			const arr = []
			for(let i = 0; i < imgArr.length; i++) {
				arr.push({
					url: imgArr[i]
				})
			}
			return arr
		},
		clickConfirmDoctorYhxy(bool = true) {
			if (bool) {
				this.show.doctorYhxy = false
				this.show.doctorYszc = true
			} else {
				this.show.doctorYhxy = true
				this.show.doctorYszc = false
			}
		},
		clickConfirmDoctorYszc(bool = true) {
			if (bool) {
				this.show.doctorYhxy = false
				this.show.doctorYszc = false
				this.show.sign = true
			} else {
				this.show.doctorYhxy = false
				this.show.doctorYszc = true
				this.show.sign = false
			}
		},
		confirmDept() {
			this.params.department = (this.curDept || this.constant.deptList[0]).text
			this.show.selectDept = false
		},
		changeDept({selectedOptions}) {
			this.curDept = selectedOptions[0]
		},
		confirmTitle() {
			this.params.title = (this.curTitle || this.constant.titleList[0]).text
			this.show.selectTitle = false
		},
		changeTitle({selectedOptions}) {
			this.curTitle = selectedOptions[0]
		},
		inputHospital() {
			this.show.hospitalPicker = false
			this.hospitalReadonly = false
			this.$refs.hospitalInput.focus()
		},
		hospitalItemClick(item) {
			if (item) {
				this.params.hospital = item.hospitalName
				this.params.hospitalId = item.id
				this.show.hospitalPicker = false
			}
		},
		signUploadSuccess({url}) {
			this.params.informedConsent = [url]
			this.show.sign = false
		},
		onSubmitHandler() {
			this.$refs.regForm.validate().then(() => {
				// this.store.dispatch('doctor/submit', {isUpdate: this.params.id ? true : false})
				showConfirmDialog({
					title: '温馨提示',
					message: '确定提交填写的注册信息么？',
				}).then(() => {
					this.params.photoJson = this.getPhotoJson()
					this.params.createUserId = sessionStorage.getItem('volunteer') || ''
          if (this.params.createUserId == 'undefined') this.params.createUserId = ''
					if (sessionStorage.getItem('isScan') === 'true'){	
						this.params.openid = sessionStorage.getItem('openid')
            const speakerId = localStorage.getItem('speakerId')
            if (speakerId) this.params.id = speakerId
						return this.api.speakerAddScan(this.params)
					}
					return this.api.speakerAdd(this.params)
					}).then(res => {
						if (!res.code) {
							if (sessionStorage.getItem('isScan') === 'true'){
								showToast('注册成功')
								this.$router.replace('/vol/register-result')
							}else {
								showToast('添加成功')
								this.$router.replace('/vol/speaker')
							}
						}
					}).catch((e) => {
						if (e === 'cancel') return
						const message = e.length ? e[0].message : '校验未通过，请确认'
						showNotify({ type: 'danger', message })
					})
				})
				.catch(() => {
				});

		},
		saveStorageHandler() {
			this.params.photoJson = this.getPhotoJson()
			this.params.createUserId = sessionStorage.getItem('volunteer') || ''
      if (this.params.createUserId == 'undefined') this.params.createUserId = ''
			
			if(sessionStorage.getItem('isScan') === 'true') {
				this.params.openid = sessionStorage.getItem('openid')
        const speakerId = localStorage.getItem('speakerId')
        if (speakerId) this.params.id = speakerId
				this.params.isScan = true
			}else {
				this.params.isScan = false
			}
      if(!this.params.name || !this.params.hospital || !this.params.department || !this.params.title) {
				showNotify({ type: 'danger', message: '暂存讲者至少需要填写讲者姓名，医院，职称，科室' })
				return false
			}
			this.api.speakerStorage(this.params).then(res => {
				if(res.code === 0) {
					localStorage.setItem('speakerId', res.data)
					showSuccessToast('暂存成功')
				}
			})
		},
		getPhotoJson() {
			return JSON.stringify([
							{
								photoType: 1,
								photoName: '身份证正面',
								url: this.params.idCardFront
							},
							{
								photoType: 2,
								photoName: '身份证反面',
								url: this.params.idCardRevers
							},
							{
								photoType: 3,
								photoName: '执业证书',
								url: this.params.licensedPhysician
							},
							{
								photoType: 4,
								photoName: '胸牌',
								url: this.params.nameBadge
							},
							{
								photoType: 5,
								photoName: '银行卡照片',
								url: this.params.bankCard
							},
							{
								photoType: 6,
								photoName: '讲者照片',
								url: this.params.avatar
							}
						])
		},
		uploadSuccIdCardFront (url) {
			this.api.ocr({
				type: 'idCard',
				fileUrl: 'http://' + url
			}).then(res => {
				if(res.code === 0) {
					showDialog({
						title: '温馨提示',
						message: '系统已识别您的身份证号，请核对识别的身份证号是否正确？\n' + res.data.name + '  ' + res.data.idNum,
						cancelButtonColor: 'red',
						showCancelButton: true,
						cancelButtonText: '不正确',
						confirmButtonText: '正确'
					}).then(() => {
						this.params.cardNumber = res.data.idNum
						this.params.name = res.data.name
					});
				}
			})
		},
		uploadSuccBankPicture (url) {
			this.api.ocr({
				type: 'bankCard',
				fileUrl: 'http://' + url
			}).then(res => {
				if(res.code === 0) {
					showDialog({
						title: '温馨提示',
						message: '系统已识别您的银行卡号，请核对识别的卡号是否正确？\n' + res.data.cardNo,
						cancelButtonColor: 'red',
						showCancelButton: true,
						cancelButtonText: '不正确',
						confirmButtonText: '正确'
					}).then(() => {
						this.params.bankNumber = res.data.cardNo
					});
				}
			})
		},
		// 图片上传成功
		uploadSucc(rowFile) {
			this.params[rowFile.type].push(rowFile.url)
			if(rowFile.type === 'idCardFront') {
				this.uploadSuccIdCardFront(rowFile.url)
			}
			if(rowFile.type === 'bankCard') {
				this.uploadSuccBankPicture(rowFile.url)
			}
		},
		// 删除图片
		deleteFile(rowFile) {
			this.params[rowFile.type].forEach((item, index) => {
                if(rowFile.url.indexOf(item) >= 0) {
                    this.params[rowFile.type].splice(index, 1)
                }
            })

			switch (rowFile.type) {
				case 'idCardFront':
					this.params.cardNumber = '';
					break;
				case 'bankPicture':
					this.params.bankNumber = '';
					break;
			}
		},

		// 点击显示参会记录
		clickShowMeetingRecord () {
			this.$refs.refMeetingRecord.init({
				t: `${this.params.name}的参会记录`,
				speakerId: this.$route.params.id
			})
		},
		computeRegStep(params) {
			let totalColumns = 0
			let completeColumns = 0
			for(let key in params) {
        if (this.hasRegisterField(key)) {
          totalColumns ++
					if(typeof params[key] === 'object') {
						if(params[key].length > 0) {
							console.log(params[key])
							completeColumns ++
						}
					} else {
						if(params[key]) {
							console.log(params[key])
							completeColumns ++
						}
					}
        }
			}
			console.log(completeColumns)
			console.log(totalColumns)
			this.fromProgress = Math.round((completeColumns/totalColumns)*100)
			// NProgress.set(fromProgress)
		}
	}
})
</script>

<style lang="less">
	.speaker_detail {
		.progress {
			background-color: #fff;
			padding: 14px 10px;
		}
		padding-top: 170px;
		padding-bottom: 50px;
		background-repeat: no-repeat;
		background-size: contain;
	}
	.speaker_detail .van-uploader__wrapper {
		justify-content: flex-end;
	}
	.speaker_detail .van-uploader__upload,
	.speaker_detail .van-uploader__preview {
		margin: 0 0 var(--van-padding-xs) var(--van-padding-xs);
	}

	.handle_fixed {
		position: fixed;
		bottom: 80px;
		width: 100%;
	}
  .avatar-preview {
    position: relative;
    &_close {
      position: absolute;
      right: 0;
      top: 0;
      width: 20px;
      height: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
      background-color: rgba(0, 0, 0, .8);
      color: #fff;
      z-index: 1;
    }
    &__inner {
      width: 88px;
      height: 88px;
      border-radius: 10px;
      vertical-align: middle;
    }
  }
</style>
